<!--

/*
* Copyright (C) 2005-2013 University of Sydney
*
* Licensed under the GNU License, Version 3.0 (the "License"); you may not use this file except
* in compliance with the License. You may obtain a copy of the License at
*
* http://www.gnu.org/licenses/gpl-3.0.txt
*
* Unless required by applicable law or agreed to in writing, software distributed under the License
* is distributed on an "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express
* or implied. See the License for the specific language governing permissions and limitations under
* the License.
*/

/**
* brief description of file
*
* @author      Tom Murtagh
* @author      Kim Jackson
* @author      Ian Johnson   <ian.johnson@sydney.edu.au>
* @author      Stephen White   <stephen.white@sydney.edu.au>
* @author      Artem Osmakov   <artem.osmakov@sydney.edu.au>
* @copyright   (C) 2005-2013 University of Sydney
* @link        http://Sydney.edu.au/Heurist
* @version     3.1.0
* @license     http://www.gnu.org/licenses/gpl-3.0.txt GNU License 3.0
* @package     Heurist academic knowledge management system
* @subpackage  !!!subpackagename for file such as Administration, Search, Edit, Application, Library
*/

-->


<html>
	<head>
        <meta http-equiv="content-type" content="text/html; charset=utf-8">
		<link rel=stylesheet href='../../common/css/global.css'>
		<title></title>
		<script src='../../external/jquery/jquery.js'></script>
		<script src='../../records/tags/usergroupTagEditorLibrary.js'></script>
		<script>
			if (top.HEURIST.search.collectCount == 0) {
				alert("No records have been collected. Please select records from the search results and press collect to add records, then press save.");
				setTimeout(function() { window.close(); }, 100);
			}

			function parseTagOnlySearches(searches) {
				var tagOnlySearches = [];
				for (var i =0; i < searches.length; i++) {
					var ss = searches[i];
					if (!ss[1]) {
						continue;
					}
					var q = ss[1].match(/[\?&]q=([^&]*)/);
					if (!q || !q[1]) {
						continue;
					}
					//q = q[1].replace(/\+/g,' ');
					q = q[1].replace(/\+?sortby:('[^']+'|"[^"]+"|\S+)/g,'');	//remove any sortby predicates
					q = q.replace(/OR(?![^:='"]+['"])/g,'');	// remove any 'OR' s not in a quoted string
					var preds = q.match(/\S+[:=](?:'[^']+'|"[^"]+"|\S+)|[^:='"\s]+/g);	//create an array of all predicates including stand alone words
					var tags = q.match(/((kwd)|(keyword)|(tag))[:=]('[^']+'|"[^"]+"|\S+)/g);	//create an array of just tag predicates
					if (!tags || preds.length != tags.length) {
						continue;
					}
					tags = tags.join(" | ").replace(/[^,\s]+[:=]/g,'').replace(/['"]/g,'');	// strip off the tags predicates
					tagOnlySearches.push([ss[0],tags]);
				}
				return tagOnlySearches;
			}

			//
			function parseOnlyCollections(searches) {
				var res = [],
				i;
				for (i =0; i < searches.length; i++) {
					var ss = searches[i];
					if (!ss[1]) {//skip saved searches that have no query string
						continue;
					}
					var q = ss[1].match(/[\?&]q=([^&]*)/); // or where the query string is empty
					if (!q || !q[1]) {
						continue;
					}

					q = q[1].replace(/\+?sortby:('[^']+'|"[^"]+"|\S+)/g,'');	//remove any sortby predicates
					q = q.replace(/OR(?![^:='"]+['"])/g,'');	// remove any 'OR' s not in a quoted string
					var preds = q.match(/\S+[:=](?:'[^']+'|"[^"]+"|\S+)|[^:='"\s]+/g);	//create an array of all predicates including stand alone words
					if(preds){
						for (var j =0; j < preds.length; j++) {
							if(preds[j].indexOf('ids:')===0){//if query begins with ids: then we say its a collection
								res.push([ss[0], i]); //name and index in top.HEURIST.user.savedSearches
								break;
							}
						}
					}
				}
				return res;
			}

			/**

			*/
			function init() {

				//fill in existing collection saved searchs
				var ss = parseOnlyCollections(top.HEURIST.user.savedSearches);
				var iHTML = '<option value="" selected disabled>select ...</option>';
				if (ss.length>0) {
					iHTML += '<optgroup label="saved collections" id="my-searches">';
					for (var i = 0; i < ss.length; i++) {
						iHTML += "<option value='" + ss[i][1] + "'>" + ss[i][0] + "</option>";
					}
					iHTML += "</optgroup>";
				}
				document.getElementById("collection-select").innerHTML = iHTML;

				// fill in tag only save searches
				iHTML = '<option value="" selected disabled>select ...</option>';
				ss = parseTagOnlySearches(top.HEURIST.user.savedSearches);
				if (ss.length) {
					iHTML += '<optgroup label="Personal saved searches" id="my-searches">';
					for (var i = 0; i < ss.length; i++) {
						iHTML += "<option value='" + ss[i][1].replace(/\+/g," ") + "'>" + ss[i][0] + "</option>";
					}
					iHTML += "</optgroup>";
				}
				//fill in worgroup selector
				for ( i = 0; i < top.HEURIST.user.workgroups.length; i++) {
					var wg = top.HEURIST.user.workgroups[i];
					if (!top.HEURIST.user.workgroupSavedSearches[wg]) {
						continue;
					}
					ss = parseTagOnlySearches(top.HEURIST.user.workgroupSavedSearches[wg]);
					if (ss.length) {
						iHTML += '<optgroup label="' + top.HEURIST.workgroups[wg].name +
						' saved searches" id="' + top.HEURIST.workgroups[wg].name.replace(/\s/g,'') + '-wg-searches">';
						for (var j = 0; j < ss.length; j++) {
							iHTML += "<option value='" + ss[j][1].replace(/\+/g," ") + "'>" + ss[j][0] + "</option>";
						}
						iHTML += "</optgroup>";
					}
				}
				document.getElementById("search-select").innerHTML = iHTML;

				iHTML = "";
				for (var i = 0; i < top.HEURIST.user.workgroups.length; i++) {
					var wg = top.HEURIST.user.workgroups[i];
					iHTML += "<option value=" + wg + ">" + top.HEURIST.workgroups[wg].name + "</option>";
				}
				document.getElementById("wg-options").innerHTML += iHTML;

				document.title += " Save collection (" + top.HEURIST.search.collectCount + " records) as Saved Search";
				setTimeout(function() { document.getElementById('ssType2').click() }, 10);
/* not used since 2012-02-13
				var tagsElt = document.getElementById('personal-tags');
				window.autocomplete = new top.HEURIST.autocomplete.AutoComplete(tagsElt, top.HEURIST.util.tagAutofill, { nonVocabularyCallback: top.HEURIST.util.showConfirmNewTag });
				var removeButton = document.getElementById("remove-button");
				var addButton = document.getElementById("add-button");

				var currWgTagsElt = document.getElementById("current-workgroup-tags");
				var allWgTagsElt = document.getElementById("all-workgroup-tags");
				HEURIST.wgTagEditor.WgTagEditor(currWgTagsElt, allWgTagsElt, addButton, removeButton);
*/
			}

/* not used since 2012-02-13
			function checkPersonalTags() {
				var tagsElem = document.getElementById("personal-tags");
				var tagsWarnStyle = document.getElementById('personal-tags-warning').style;
				if (tagsElem.value && tagsWarnStyle.display) {
					tagsWarnStyle.display = "";
				} else if (!tagsElem.value && !tagsWarnStyle.display) {
					tagsWarnStyle.display = "none";
				}
			}*/

			function keypress(e) {
				if (! e)
					e = window.event;
				var code = e.keyCode;
				if (e.which)
					code = e.which;
				// " and '
				if (code == 34  ||  code == 39)
					return false;

				switchModeNew();
			}

			/**
			  use form actionHandler.php via search.executeAction
			*/
			function save()
			{

				var saction;

				var ss_name, ss_query, ss_wgid, ss_id, ss_kwds;

				var rec_ids = top.HEURIST.search.collection;

				if($("#ssType2").attr('checked')){  //add to existing collection

					saction = "save_search";

					var elem = document.getElementById("collection-select");
					var index = Number(elem.value);


					if (isNaN(index) || index < 0) {
						alert("You must select the existing collection to add to.");
						return;
					}

					var ss = top.HEURIST.user.savedSearches[index];

					ss_id = ss[2];
					ss_name = elem.options[elem.selectedIndex].text;

					var m = ss[1].match(/ids:([^&]*)/);
					var ex_rec_ids = m[1];

					function _unique(array){
    					return $.grep(array,function(el,index){
        									return index == $.inArray(el,array);
    									});
    				};
					var arr = (ex_rec_ids+","+rec_ids.join(',')).split(",");
					arr = _unique(arr);

					var q = ss[1].replace(/ids:([^&]*)/ , "ids:"+arr.join(","));

					ss_query = q;

				}else if ($("#ssType1").attr('checked')) { // Create new collection

					saction = "save_search";
					ss_name = document.getElementById("search-name").value;
					ss_wgid = document.getElementById("wg-select").value;

					if (!ss_name) {
						alert("You must enter name for the saved-search before saying.");
						return;
					}


					var query = new Array();
					//ARTEM 2012-10-12 if (ss_wgid > 0 ){

						var bkmk_only = document.getElementById("bookmark-check");

						if (!bkmk_only.checked){
							//for workgroup searches overwrite with all records search
							query.push("w=all");
						} else {
							query.push("w=bookmark");
							//ARTEM 2012-10-12 rec_ids = rec_ids + " user:" + top.HEURIST.get_user_id();
						}
					//}
					query.push("q=ids:"+rec_ids.join(','));

					for (var p in top.HEURIST.parameters) { //remove it at all????
						if (p != "label" && p != "sid" && p != "db" && p != "w" && p != "q") {
							query.push(p + "=" + encodeURIComponent(top.HEURIST.parameters[p]));
						}
					}

					var result_style = document.getElementById("result-style-select").value;
					if (result_style) {
						query.push("view=" + result_style);
					}

					ss_query = "?" + query.join("&");

				}else if (false){ //not used since 2012-02-13

					saction = "bookmark_tag_and_ssearch";
					ss_name = document.getElementById("search-name").value;
					if (!ss_name) {
						alert("You must enter name for the saved-search before saying.");
						return;
					}
					ss_wgid = document.getElementById("wg-select").value;
					ss_kwds = $('#personal-tags').val();
					var kwdsRowTDs = $('#current-workgroup-tags td');
					for (var i=0; i < kwdsRowTDs.length; i++) {
						if (ss_kwds) {
							ss_kwds += ',';
						}
						ss_kwds += kwdsRowTDs[i++].innerHTML + '\\' + kwdsRowTDs[i].innerHTML;
					}
					var query = [];
					if (!ss_kwds) {
						alert("You must enter or select at least one tag to save a search.");
						return;
					}else{
						var tags = ss_kwds.split(',');
						var q = "";
						for (var j=0; j < tags.length; j++) {
							q += 'tag:"' + tags[j].replace(/^\s*/,'').replace(/\s*$/,'') + '" ';
						}
						query.push('q=' + encodeURIComponent(q));
					}
					var result_style = document.getElementById("result-style-select").value;
					if ($('#result-style-select').val()) {
						query.push("view=" + $('#result-style-select').val());
					}
					query.push("w=" + $("input[name='w']:checked").val());
					ss_query = "?" + query.join("&");



				}else{	//tag collections so they show up in an exisitng tag only saved search
					saction = "bookmark_and_tag";
					ss_kwds = $('#search-tag-list').text().replace(/\s\|\s/,',');
				}



				var _data = {rec_ids:rec_ids, svs_Name:ss_name,  svs_Query:ss_query, svs_UGrpID:ss_wgid, svs_ID:ss_id, tagString:ss_kwds};

				top.HEURIST.search.executeAction(saction, _data);
				window.close();
			}

			//
			// enable-disable components according to current mode
			//
			function switchMode(toID,arrFromID,focusID) {
				$('#'+toID).removeClass('bggray');
				var enableID = '#' + toID + "_span";
				$( enableID + " input, " + enableID + " select").attr("disabled",false);
				//$(enableID + " .wgtag-list tr").show();

				for(var ind in arrFromID)
				if(!top.HEURIST.util.isnull(ind)){
					var fromID = arrFromID[ind]
					$('#'+fromID).addClass('bggray');
					var disableID = '#' + fromID + "_span";
					$( disableID + " input, " + disableID + " select").attr("disabled",true);
					//$(disableID + " .wgtag-list tr").hide();
				}

				$('#'+focusID).focus();
			}

			//
			//
			//
			function switchModeNew() {
				switchMode('create_new_search',['add_to_collection','add_to_search'],'search-name');
				$("#ssType1").attr('checked', true);
			}

			//
			//
			//
			function displayBookmarkCheck(){
				switchModeNew();
				var vis = (document.getElementById("wg-select").value=="")?'block':'none';
				document.getElementById('bookmark-check-span').style.display = vis;
					document.getElementById('bookmark-warning').style.display = (vis=='block' && document.getElementById('bookmark-check').checked)?'block':'none';
			}

			//
			//
			//
			function showTagInfo(event){
				var elem = event.target;
				//document.getElementById('divTagInfo').style.display = (elem.value!='')?'block':'none';
				document.getElementById('divTagInfo').style.visibility = (elem.value!='')?'visible':'hidden';
				document.getElementById('search-tag-list').innerHTML = elem.value; //.options[this.selectedIndex].value;
				return false;
			}


		</script>
	</head>

	<body class="popup" onload="init();">
<!-- not used since 2012-02-13
		<script src='../../records/tags/autocompleteTags.js'></script>
-->
		<div id="add_to_collection" style="padding:10px 0">
				<input type="radio" name="ssType" id="ssType2" value="2" checked="checked"
				onclick="switchMode('add_to_collection',['add_to_search','create_new_search'],'collection-select');"
				style="float:left;">
				<label for="ssType2" style="padding-left:5px;float:left;min-width:180px;font-weight:bold;">Add to existing collection</label>
				<span id="add_to_collection_span">
					<select id="collection-select" style="width:150px">
					</select>
				</span>
		</div>

		<div class="separator_row" style="margin-bottom:20px"></div>

		<div id="add_to_search" style="padding:10px 0">
				<input type="radio" name="ssType" id="ssType0" value="0"
				onclick="switchMode('add_to_search',['add_to_collection','create_new_search'],'search-select');"
				style="float:left;">
				<label for="ssType0" style="padding-left:5px;float:left;min-width:180px;font-weight:bold;">Add to existing saved search</label>
				<span id="add_to_search_span">
					<select id="search-select" style="width:150px" onchange="showTagInfo(event);">
					</select>
					<span class="help prompt" style="margin-left:5px" >
						Only tag-based searches can be used
					</span><br/>
					<div style="margin:10px 0; visibility:hidden;" id="divTagInfo">
						<span style="margin-left: 16px;">The following tag(s) will be added: </span>
						<span id="search-tag-list" style="color: #6A7C99" ></span>
					</div>
				</span>
		</div>

		<div class="separator_row" style="margin-bottom:20px"></div>

		<div id="create_new_search">
			<input type="radio" name="ssType" id="ssType1" value="1"
					onclick="switchModeNew()">&nbsp;<label for="ssType1"><b>Create new collection</b></label><br/>
			<div style="margin-left:16px">
					<div class="div-section">
						<div style="width:170px; text-align:right; display:inline-block">Name for this search:</div>
						<input style="width:150px;height: 17px; margin-left: 5px;" type=text id=search-name onkeypress="return keypress(event)">
						<span id="bookmark-check-span" style="float: right; margin-right: 107px;">
							<input type="checkbox" id="bookmark-check" onclick="document.getElementById('bookmark-warning').style.display = this.checked?'block':'none';">
							<label for="bookmark">&nbsp;Add to My Bookmarks</label><br/>
						</span>
					</div>
					<div class="div-section">
						<div style="width:170px; text-align:right; display:inline-block">Add search to:</div>
						<select id=wg-select onChange="displayBookmarkCheck();" style="width:150px;margin-left: 5px; height: 17px;">
							<option value="">personal saved searches</option>
							<optgroup label="workgroup saved searches" id=wg-options></optgroup>
						</select>
						<span style="float: right; margin-right: 56px;">
							<span class="warning-message" id="bookmark-warning" style="margin-left: 25px; display: none;">&nbsp;records in collection will be bookmarked</span>
						</span>
					</div>
					<div class="div-section">
						<div style="width:170px; text-align:right; display:inline-block">Default result style:</div>
						<select id=result-style-select style="width:150px;margin-left: 5px; height: 17px;">
							<option value="" selected>Status quo</option>
							<option value=list>One column</option>
							<option value=two-col>Two columns</option>
							<option value=icon>Icon</option>
							<option value=thumbs>Thumbnails</option>
							<option value=blog disabled>Blog</option>
						</select>
					</div>


<!--
			<div class="div-section">
					<div style="width:125px; text-align:right; display:inline-block">Personal tag(s)</div>
					<input style="width:150px;height: 17px; margin-left:5px" type=text id="personal-tags" onkeypress="setTimeout(function(){checkPersonalTags();},10); return true;"><span class="warning-message" id="personal-tags-warning" style="margin-left: 5px; display:none;">records in collection will be bookmarked</span>
				<div class="help prompt" style="margin-left:133px">
				Note: any records with these tags will be included in the saved search
					</div>
				<div class="div-section" style="margin-top:20px">
						<span style="float: left; margin: 0;">Workgroup tag(s) &nbsp;&nbsp;</span>
						<span class="help prompt" >
							Use for personal or workgroup saved searches.
						</span>

						<br clear=all>

						<table border=0 cellspacing=0 cellpadding=0 style="margin: 10px 0;">
							<tr>
							<td style="width:45%;"><b>Available</b></td>
							<td style="width:10%;"></td>
							<td style="width:45%;"><b>Selected</b></td>
							</tr>

							<tr>
								<td>
								<div class=wgtag-list style="height:150px;"><table border=0 cellspacing=0 cellpadding=0><tbody id=all-workgroup-tags></tbody></table></div>
								</td>
								<td>
								<div id=button-box style="text-align:center; padding:0">
									<div style="padding:5px"><input type=button value="&gt;" title="Add a tag" onmousedown="HEURIST.wgTagEditor.addWgTag(window.selectedRow)" disabled id=add-button></div>
									<div style="padding:5px"><input type=button value="&lt;" title="Remove a tag" onmousedown="HEURIST.wgTagEditor.removeWgTag(window.selectedRow)" disabled id=remove-button></div>
									</div>
								</td>
								<td>
								<div class=wgtag-list style="height:150px;"><table border=0 cellspacing=0 cellpadding=0><tbody id=current-workgroup-tags></tbody></table></div>
								</td>
							</tr>

							<tr class=help>
								<td class=prompt>Double-click to add a tag</td>
								<td>&nbsp;&nbsp;</td>
								<td class=prompt>Double-click to deselect a tag</td>
							</tr>
							<tr><td>
									<div id="admin-wgTags"><br><a href="../../admin/ugrps/editGroupTags.php" target="_blank">add/delete</a> tags for workgroups (administrators only). </div>
							</td></tr>
						</table>

						<form id=wgtag-form onsubmit="return false;"></form>

					</div>
				</div>
-->
			</div>
		</div>

		<div class="separator_row" style="margin:20px 0"></div>

		<p>
			<input type=button value=Cancel id=btnCancel onclick="window.close();" style="float: right; margin-right: 30px;">
			<input type=button value=Save id=btnSave onclick="save();" style="float: right;margin-right: 4px;">
		</p>

	</body>

</html>
